import { _decorator, Component, Node, Prefab, ParticleUtils, ParticleSystemComponent, instantiate } from "cc";
import { CustomerEventListener } from "../data/CustomerEventListener";
import { Constants } from "../data/Constants";
import { PoolManager } from "../data/PoolManager";
const { ccclass, property } = _decorator;

@ccclass("EffectManager")
export class EffectManager extends Component {

    @property({ type: Prefab, tooltip: '刹车皮特效-预制体' })
    brakeTrialPrefab: Prefab = null;

    @property({ type: Prefab, tooltip: '金币特效-预制体' })
    coinPrefab: Prefab = null;

    // 尾气跟随对象（小车）
    private followTarget: Node = null;
    // 刹车皮
    private currBraking: Node = null;

    // 金币特效
    private coinEffect: ParticleSystemComponent = null;

    start(): void {
        CustomerEventListener.on(Constants.EventName.BRAKE_START, this.brakeStart, this);
        CustomerEventListener.on(Constants.EventName.BRAKE_STOP, this.brakeEnd, this);
        CustomerEventListener.on(Constants.EventName.SHOW_COIN, this.showCoin, this);
    }

    update(): void {
        if (this.currBraking && this.followTarget) {
            this.currBraking.setWorldPosition(this.followTarget.worldPosition);
        }
    }

    private brakeStart(...args: any[]): void {
        console.log("### brakeStart")
        const pos = args[0];
        const follow = args[0];
        this.followTarget = args[0];
        this.currBraking = PoolManager.getNode(this.brakeTrialPrefab, this.node);
        this.currBraking.setWorldPosition(follow);
        ParticleUtils.play(this.currBraking);
    }

    private brakeEnd(): void {
        console.log("### brakeEnd")
        const tempCurrBraking = this.currBraking;
        ParticleUtils.stop(tempCurrBraking);
        this.scheduleOnce(() => {
            PoolManager.setNode(tempCurrBraking);
        }, 2);
        this.currBraking = null;
        this.followTarget = null;
    }

    private showCoin(...args: any[]): void {
        const pos = args[0];
        if (!this.coinEffect) {
            const coin = instantiate(this.coinPrefab) as Node;
            coin.setParent(this.node);
            this.coinEffect = coin.getComponent(ParticleSystemComponent);
        }

        this.coinEffect.node.setWorldPosition(pos);
        this.coinEffect.play();
    }

}
